<?php

namespace App\Http\Controllers;

use App\Modules\User\Models\User;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Cookie;
use JWTAuth;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;


    /**
     * 是否未登录
     * @return bool true:未登录
     */
    protected function isNotLogin() {
        $user = self::getAuthenticatedUser();
        if($user) {
            return false;
        }
        return true;
    }

    protected function getLoginUserId() {
        $user = self::getAuthenticatedUser();
        if ($user) {
            return $user->id;
        }
        return 0;
    }

    protected function getLoginUserWechatOpenId() {
        $user = self::getAuthenticatedUser();
        if ($user) {
            $wechatUser = User::getUserInfo($user->id);
            return $wechatUser->openid;
        }
        return false;
        //return 'onizM4rt0jDrst6sNCLxCGUa9UrQ';
    }

    protected function getLoginUser() {
        return self::getAuthenticatedUser();
    }

    public static function getAuthenticatedUser(){
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return false;
            }
            return $user;
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return false;
            //return response()->json(['token_expired'], $e->getStatusCode());
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return false;
            //return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            return false;
            //return response()->json(['token_absent'], $e->getStatusCode());
        } catch (\Exception $e) {
            //return false;
        }
        return false;
    }






    public function getParameterStartTime(Request $request) {
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Ymd',strtotime($request->input('start_time'))) : '';
        return $start_time;
    }

    public function getParameterEndTime(Request $request) {
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Ymd',strtotime($request->input('end_time'))) : '';
        $end_time = self::getMaxDay($end_time);

        return $end_time;
    }

    /**
     * 获取今天最大时间
     * @param string $dayTime
     * @return mixed
     */
    public static function getMaxDay($dayTime = '') {
        if(!empty($dayTime) && (strlen(trim($dayTime)) == 8 || strlen(trim($dayTime)) == 10)) {
            $dayTime = $dayTime." 23:59:59";
        }
        return $dayTime;
    }
}
